<template>
	<BasicDrawer v-model:show="showModal" :title="menuTitle" :width="'80%'">
		<n-form ref="formRef" :label-width="80" :model="form" :rules="rules" size="medium">
			<n-form-item label="部门名称" path="depart_name">
				<n-input v-model:value="form.depart_name" placeholder="请输入部门名称" />
			</n-form-item>
			<n-form-item label="部门描述" path="depart_details">
				<n-input v-model:value="form.depart_details" placeholder="请输入部门描述" />
			</n-form-item>
			<n-form-item label="父id" path="pid">
				<n-input v-model:value="form.pid" disabled placeholder="请输入父id" />
			</n-form-item>
			<n-form-item label="层级id" path="id_path">
				<n-input v-model:value="form.id_path" disabled placeholder="请输入层级id" />
			</n-form-item>
		</n-form>
		<template v-slot:footer>
			<n-button @click="handleCancel">取消</n-button>
			<n-button class="ml-10" @click="handleConfirm" :loading="btnLoading" type="primary">确定</n-button>
		</template>
	</BasicDrawer>
</template>

<script setup lang="ts">
	import { unref, ref, reactive, defineExpose } from 'vue'
	import { useMessage, NButton, FormInst } from 'naive-ui'
	import { BasicDrawer } from "@/components/Common/BasicDrawer"
	import _ from "lodash-es"
	import { RowData } from 'naive-ui/es/data-table/src/interface'
	import { addOrUpdateDepart } from "@/api/system"
	const message = useMessage()
	const emits = defineEmits([
		"refresh"
	])
	const showModal = ref(false)
	const roleId = ref<string>()
	const formRef = ref<FormInst | null>(null)
	const formData = () => ({
		depart_name: null,
		depart_details: null,
		pid: null
	})
	let form = reactive(formData())
	const rules = {
		depart_name: {
			required: true,
			trigger: ['blur', 'input'],
			message: '请输入部门名称'
		}
	}
	const menuTitle = ref<String>("用户新增")
	/**
	 * @param {Object} row
	 * 打开弹窗
	 */
	function open(row : RowData, flag) {
		showModal.value = true
		if (!flag) {
			menuTitle.value = '部门编辑'
			roleId.value = row.id
			Object.assign(unref(form), row)
		} else {
			form = Object.assign(unref(form), formData())
			formRef.value?.restoreValidation()
			if (row) {
				form.pid = row.id
				form.id = ''
				if (row.pid === '0') {
					form.id_path = row.pid + "," + row.id
				} else {
					form.id_path = row.id_path + "," + row.id
				}
			
			}
			menuTitle.value = '部门新增'
		}
	}
	function handleCancel() {
		showModal.value = false
	}
	/**
	 * 保存
	 */
	const btnLoading = ref<Boolean>(false)
	function handleConfirm(e : MouseEvent) {
		e.preventDefault()
		formRef.value?.validate((errors) => {
			if (!errors) {
				btnLoading.value = true
				addOrUpdateDepart(form).then(() => {
					message.success('保存成功')
					btnLoading.value = false
					showModal.value = false
					emits('refresh')
				})
			} else {
				message.error('验证失败')
			}
		})

	}

	defineExpose({
		open
	})
</script>

<style>
</style>